package com.ruoyi.system.utils;

import cn.hutool.json.JSONUtil;
import com.ruoyi.system.domain.SysContracts;
import io.netty.handler.codec.mqtt.MqttQoS;
import io.vertx.core.Future;
import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
import io.vertx.mqtt.MqttClient;
import io.vertx.mqtt.messages.MqttConnAckMessage;
import io.vertx.mqtt.messages.MqttMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.List;

@Component
@Slf4j
public class MyMqttClient {
    private String ip="127.0.0.1";
    private int port=1883;

    private MqttClient mqttClient;
    public void myMqttClient(String topic,List<SysContracts> contracts){
        Vertx vertx = Vertx.vertx();
        mqttClient = MqttClient.create(vertx);
        mqttClient.connect(port, ip, res -> {
            if(res.succeeded()){
                log.info("connect to mqtt ip:{},port:{}","127.0.0.1",1883);
                MqttConnAckMessage mqttConnAckMessage = res.result();
                String s = JSONUtil.toJsonStr(contracts);
                mqttClient.publish(topic, Buffer.buffer(s), MqttQoS.AT_MOST_ONCE, false, false);
            }else {
                log.warn("[fail] connect to mqtt ip:{},port:{}",ip,port);
            }
        }).exceptionHandler(throwable -> System.out.println("连接mqtt异常"));
    }


}
